package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.File;
import com.kaishengit.entity.FileType;
import com.kaishengit.util.db.DBHelp;
import com.kaishengit.util.db.Page;
import com.kaishengit.util.db.RowMapper;

public class FileDao {
	
	private DBHelp<File> db = new DBHelp<File>();
	
	public void save(File file){
		String sql="insert into t_file(id,name,filename,filesize,createtime,filetypeid,userid)value(?,?,?,?,?,?,?)";
		db.executeSQL(sql, file.getId(),file.getName(),file.getFilename(),file.getFilesize(),file.getUserid(),file.getFiletypeid());
	}
	
	public void update(File file){
		String sql="update t_file set name=?,filename=?,filesize=?,createtime=?,filetypeid=?,userid=? where id=?";
		db.executeSQL(sql, file.getName(),file.getFilename(),file.getFilesize(),file.getCreatetime(),file.getFiletypeid(),file.getUserid());
	}
	public void del(String id){
		String sql="delete from t_file where id=?";
		db.executeSQL(sql, id);
	}
	public List<File> findAll(){
		String sql="select id,name,filename,filesize,filetypeid,userid, from t_file createtime order by createtime desc";
		return db.executeQueryToList(sql, new FileRowMapper());
		
	}
	public File findById(String id){
		String sql="select id ,name,filename,filesize,filetyoeid,userid,createtime  from t_file where id=? order by createtime desc";
		return db.executeQueryToObject(sql, new FileRowMapper(),id);
		
		
	}
	
	
	
	public class FileRowMapper implements RowMapper<File>{

		public File mapRow(ResultSet rs) throws SQLException {
			File file = new File();
			file.setId(rs.getString("id"));
			file.setName(rs.getString("name"));
			file.setCreatetime(rs.getString("cratetime"));
			file.setFilename(rs.getString("filename"));
			file.setFilesize(rs.getShort("filesize"));
			file.setFiletypeid(rs.getString("filetypeid"));
			file.setUserid(rs.getString("userid"));
			
			
			return file;
		}
		
	}



	public Page<File> findByPage(String filetypeid, int pageNum) {
		Page<File> page = new Page<File>(count(filetypeid),pageNum);
		String sql="select id,filename,filesize,name,createtime,projectid,userid from t_file where filetypeid  = ? limit ?,?";
		List<File> list = db.executeQueryToList(sql, new FileRowMapper(), filetypeid,page.getStart(), page.getPageSize());
		page.setList(list);
		return page;
	}

	private int count(String filetypeid) {
		String sql="select count(*) from t_file where filetypeid  = ? ";
		return db.executeQuery(sql,filetypeid).intValue();
	}

	



	
}
